import router, { constantRoutes } from '@/router';
import store from '@/store';
import { getToken } from '@/utils/auth'; // get token from cookie
import { getClientAuth } from './clientAuth';
import { getLocalData } from '@/utils/localStore';

const whiteList = constantRoutes.map(item => item.path); // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  const client = getLocalData('client');
  const isClient = client && Object.keys(client).length > 0;
  const toPath = to.path;
  if (!!(to.query.xxf && !from.name) || isClient) {
    // 客户端需要直接访问的页面，在进入页面前需要先拿到授权
    try {
      console.log('准备获取客户端授权...');
      const clientAuthInfo = await getClientAuth();
      console.log('获取到授权：', clientAuthInfo);
      const { organId } = store.getters['user/userInfo'];
      if (!organId || organId !== clientAuthInfo.userInfo.companyId) {
        await store.dispatch('user/setClientAuth', clientAuthInfo); // 设置由客户端携带的token和用户信息
        await store.dispatch('organization/initOrgTree', clientAuthInfo.userInfo.companyId); // 登录后在store中初始化组织信息
      }
      if (toPath !== '/dashboard' && !whiteList.includes(toPath)) {
        await store.dispatch('tags/addTag', to);
      }
      next();
    } catch (error) {
      console.log('客户端授权失败...');
      next();
    }
  } else {
    const hasToken = getToken();
    if (hasToken) {
      if (toPath === '/login') {
        next('/');
      } else {
        // const { organId } = store.getters['user/userInfo'];
        // await store.dispatch('organization/initOrgTree', organId); // 登录后在store中初始化组织信息
        if (toPath !== '/dashboard' && !whiteList.includes(toPath)) {
          await store.dispatch('tags/addTag', to);
        }
        next();
      }
    } else {
      if (whiteList.includes(to.path) || isClient) {
        next();
      } else {
        await store.dispatch('user/removeAccessToken'); // 清除遗留的token记录
        next('/401'); // 其他页面未授权是统一跳转到401
      }
    }
  }
});
